#!/usr/bin/python3
import gc
import os
from openpyxl import load_workbook
import json
from .Base_Plugin import Base_Plugin


class Lookup_Type:
    def __init__(
        self,
        code: str,
        name_cn: str,
        name_en: str,
        sort_number: int,
        status,
    ) -> None:
        self.SPACE = " "
        self.code = code
        self.name = json.dumps(
            obj={"cn": name_cn, "en": name_en},
            ensure_ascii=False,
            separators=(",", ":"),
        )
        self.sort_number = sort_number
        self.status = 1 if status == "Y" else 0

    def sql(self, tenant):
        if tenant is None:
            table_name = "config_lookup_type"
        else:
            table_name = "{}{}config_lookup_type{}{}".format(
                tenant["table_prefix"],
                tenant["delimiter"],
                tenant["delimiter"],
                tenant["tenant_id"],
            )
        return "INSERT INTO {} (code, `name`, sort_number, `status`) VALUES ('{}', '{}', {}, {});".format(
            table_name,
            self.code,
            self.name,
            self.sort_number,
            self.status,
        )


class Lookup_Item:
    def __init__(
        self,
        lookup_type_code: str,
        code: str,
        name_cn: str,
        name_en: str,
        addition: str,
        status,
        sort_number: int,
    ) -> None:
        self.SPACE = " "
        self.lookup_type_code = lookup_type_code
        self.code = code
        self.name = json.dumps(
            obj={"cn": name_cn, "en": name_en},
            ensure_ascii=False,
            separators=(",", ":"),
        )
        if addition is not None:
            self.addition = json.dumps(json.loads(addition))
        else:
            self.addition = None
        self.status = 1 if status == "Y" else 0
        self.sort_number = sort_number

    def sql(self, tenant):
        if tenant is None:
            table_name = "config_lookup_item"
        else:
            table_name = "{}{}config_lookup_item{}{}".format(
                tenant["table_prefix"],
                tenant["delimiter"],
                tenant["delimiter"],
                tenant["tenant_id"],
            )
        return "INSERT INTO {} (lookup_type_code, code, `name`, addition, sort_number, `status`) VALUES ('{}', '{}', '{}', {}, {}, {});".format(
            table_name,
            self.lookup_type_code,
            self.code,
            self.name,
            "'{}'".format(self.addition) if self.addition is not None else "NULL",
            self.sort_number,
            self.status,
        )


class Generate_Lookup_SQL_Script(Base_Plugin):
    """生成快码SQL插件"""

    def __init__(self, context) -> None:
        super().__init__()
        self.context = context

    def save_file(self, sql, dir):
        with open(dir, "w", encoding="utf-8") as f:
            f.write(sql)

    def clean_sql(self, table_name, tenant):
        if tenant is not None:
            table_name = "{}{}{}{}{}".format(
                tenant["table_prefix"],
                tenant["delimiter"],
                table_name,
                tenant["delimiter"],
                tenant["tenant_id"],
            )
        return "DELETE FROM {};".format(table_name)

    def run(self, workspace, source):
        _target_path = os.path.join(workspace, "sql")
        if not os.path.exists(_target_path):
            os.makedirs(_target_path)
        workbook = load_workbook(os.path.join(workspace, source))
        _lookup_type = workbook["数据字典组"]
        _lookup_item = workbook["数据字典项"]
        lookup_type_sort_number_start = 1
        lookup_item_sort_number_start = 1

        lookup_sql = list()
        lookup_tenant_sql = list()
        lookup_sql.append(self.clean_sql("config_lookup_type", None))
        lookup_tenant_sql.append(
            self.clean_sql("config_lookup_type", self.context["init_tenant"])
        )
        type_code_list = list()
        for row in _lookup_type.rows:
            if row[0].row < self.project_config["通用开始行"]:
                continue
            assert row[0].value not in type_code_list, self.error_log(row[0].value)
            type_code_list.append(row[0].value)

            lookup_type = Lookup_Type(
                row[0].value,
                row[1].value,
                row[2].value,
                lookup_type_sort_number_start,
                row[3].value,
            )
            lookup_type_sort_number_start += 1
            lookup_sql.append(lookup_type.sql(None))
            lookup_tenant_sql.append(lookup_type.sql(self.context["init_tenant"]))
            self.processed += 1

        lookup_sql.append(self.clean_sql("config_lookup_item", None))
        lookup_tenant_sql.append(
            self.clean_sql("config_lookup_item", self.context["init_tenant"])
        )
        item_code_list = list()

        for row in _lookup_item.rows:
            if row[0].row < self.project_config["通用开始行"]:
                continue
            assert row[0].value in type_code_list, self.error_log(row[0].value)
            assert row[1].value not in item_code_list, self.error_log(row[0].value)
            item_code_list.append(row[1].value)

            lookup_item = Lookup_Item(
                row[0].value,
                row[1].value,
                row[2].value,
                row[3].value,
                row[4].value,
                row[5].value,
                lookup_item_sort_number_start,
            )
            lookup_item_sort_number_start += 1
            lookup_sql.append(lookup_item.sql(None))
            lookup_tenant_sql.append(lookup_item.sql(self.context["init_tenant"]))
            self.processed += 1

        lookup_sql = "\n".join(lookup_sql)
        lookup_tenant_sql = "\n".join(lookup_tenant_sql)
        self.save_file(
            lookup_sql,
            os.path.join(
                _target_path,
                "lookup.sql",
            ),
        )
        self.save_file(
            lookup_tenant_sql,
            os.path.join(
                _target_path,
                "lookup-tenant.sql",
            ),
        )

        del workbook
        gc.collect()
        return source
